package com.jnu.experience07;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.jnu.experience07.views.GameView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link GameFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GameFragment extends Fragment {
    private GameView gameView;
    private FrameLayout mFrame;
    private Button leftButton;
    private Button rightButton;
    private Button bombButton;
    private Button pauseButton;
    private View gameWidgets;
    private TextView ammoText;
    private TextView scoreText;
    private MyReceiver receiver = null;	//接收GameView的更新信息，用于更新UI数据
    private int score;
    private AlertDialog alertDialog;

    public GameFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment GameFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static GameFragment newInstance() {
        GameFragment fragment = new GameFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @SuppressLint({"ClickableViewAccessibility", "UseCompatLoadingForDrawables"})
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_game, container, false);
        score = 0;
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(GameView.UPDATE_AMMO);
        filter.addAction(GameView.UPDATE_SCORE_10);
        this.getContext().registerReceiver(receiver, filter);
        alertDialog = new AlertDialog.Builder(GameFragment.this.getContext()).create();
        LayoutInflater inflater1 = (LayoutInflater)this.getContext().getApplicationContext().getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        gameWidgets = inflater1.inflate(R.layout.fragment_game,null);
        ammoText = (TextView) gameWidgets.findViewById(R.id.ammoText);
        scoreText = (TextView) gameWidgets.findViewById(R.id.scoreText);
        leftButton = (Button) gameWidgets.findViewById(R.id.button1);

        leftButton.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    gameView.setDirection(GameView.STOP);
                    return true;
                } else if(event.getAction() == MotionEvent.ACTION_DOWN){
                    gameView.setDirection(GameView.LEFT);
                    return true;
                }
                return false;
            }

        });
        rightButton = (Button) gameWidgets.findViewById(R.id.button2);
        rightButton.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    gameView.setDirection(GameView.STOP);
                    return true;
                } else if(event.getAction() == MotionEvent.ACTION_DOWN){
                    gameView.setDirection(GameView.RIGHT);
                    return true;
                }
                return false;
            }

        });

        bombButton = (Button) gameWidgets.findViewById(R.id.button3);
        bombButton.setOnClickListener(new OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                gameView.createBomb();
                int ammo = gameView.getAmmoCount();
                ammoText.setText("X" + ammo);
            }

        });

        pauseButton = (Button) gameWidgets.findViewById(R.id.pause_button);
        gameView = new GameView(GameFragment.this.getContext());
        mFrame = new FrameLayout(GameFragment.this.getContext());
        mFrame.addView(gameView);
        mFrame.addView(gameWidgets);
        mFrame.setBackground(getResources().getDrawable(R.drawable.bg));
        this.getActivity().setContentView(mFrame);
        pauseButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                gameView.pauseGame();
                alertDialog.setMessage("Game paused");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Resume",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                gameView.resumeGame();
                            }
                        });
                alertDialog.show();
            }

        });
        alertDialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                gameView.resumeGame();
            }

        });

        return rootView;
       // return inflater.inflate(R.layout.fragment_game, container, false);
    }
    public class MyReceiver extends BroadcastReceiver
    {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (intent.getAction().equals(GameView.UPDATE_AMMO))
            {
                int ammo = gameView.getAmmoCount();
                ammoText.setText("X" + ammo);
            }  else if(intent.getAction().equals(GameView.UPDATE_SCORE_10)) {
                score += 10;
                scoreText.setText("Score:" + score);
            }
        }

    }

    public void onStop() {
        super.onStop();
        gameView.surfaceDestroyed(gameView.getSurfaceHolder());
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return onKeyDown(keyCode, event);
        }

        return onKeyDown(keyCode, event);
    }

    public void onDestroy() {
        super.onDestroy();
        if(receiver!=null)
            this.getContext().unregisterReceiver(receiver);
    }
}